<template>
  <md-nav-bar title="资讯详情" />
  <view class="container">
    <view class="top_desc">
      <view class="title ellipsis-2">{{ data.info?.title }}</view>
      <view class="date m-top-26">
        <view class="flex-b">
          <view class="flex-l">
            <md-icon name="clock" width="30" height="30" />
            {{ data.info?.starttime + ' ~ ' + data.info?.endtime }}
          </view>
          <button class="m-all-0 p-all-0 raidus-lg" open-type="share">
            <md-icon :url="data.configInfo?.share_icon" width="140" height="64" />
          </button>
        </view>
      </view>
      <!-- 富文本 -->
      <view class="content" style="width: 100%; height: auto">
        <rich-text :nodes="data.info?.content"></rich-text>
      </view>
    </view>
    <view class="comment-list m-top-20">
      <mescroll-body @init="mescrollInit" @down="downCallback" @up="upCallback" safearea bottom="120rpx">
        <CommentList :list="data.list" @reply="handleReply" @del="handleDel"></CommentList>
      </mescroll-body>
    </view>
    <!-- 底部按钮 -->
    <view class="btn">
      <view style="width: 100%" @click="() => (data.review_id = null)">
        <input
          v-model="data.content"
          class="input"
          :placeholder="data.placeholder"
          confirm-type="send"
          :focus="data.focus"
          @blur="onBlur"
          @confirm="handleSend" />
      </view>
      <!-- 点赞 -->
      <view v-if="data.info" class="m-left-12" @click.stop="() => handleCollect(data.info, 2)">
        <md-dianzan :text="data.info.agree_num" collectKey="is_agree" :item="data.info" />
      </view>
      <!-- 收藏 -->
      <view v-if="data.info" class="m-left-12" @click.stop="() => handleCollect(data.info, 1)">
        <md-dianzan type="collect" :text="data.info.collect_num" :item="data.info" />
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { onLoad, onShareAppMessage, onPageScroll, onReachBottom } from '@dcloudio/uni-app';
import { reactive } from 'vue';
// 组件
import CommentList from '@/components/comment-list/index.vue';
import useMescroll from '@/uni_modules/mescroll-uni/hooks/useMescroll.js';
// 接口
import { newsCollect, newsDelReview, newsDetail, newsReview, newsReviewList } from '@/api';
import type { Interaction } from '@/api/data';
// 工具
import { Toast } from '@/utils/util';
const { mescrollInit, downCallback, getMescroll } = useMescroll(onPageScroll, onReachBottom);

const data = reactive<any>({
  id: -1,
  info: {},
  status: false,
  collectStauts: false,
  // 回复评论相关
  list: [],
  total: 0,
  review_id: null,
  content: '',
  focus: false,
  placeholder: '我有话要说...',
  configInfo: {},
});

// 分享钩子
onShareAppMessage(res => {
  return {
    title: '资讯详情',
    // imageUrl: data.configInfo?.share_poster,
    path: '/pages/news/detail?id=' + data.id,
  };
});

// 收藏 | 点赞回调
const handleCollect = async (item: Interaction.Index.Data, type: number) => {
  // 1收藏 2点赞
  const typeCode = type === 1 ? 'collect' : 'agree';
  item[`is_${typeCode}`] = !item[`is_${typeCode}`];
  if (!!item[`is_${typeCode}`]) {
    item[`${typeCode}_num`] += 1;
  } else {
    item[`${typeCode}_num`] -= 1;
  }
  const res = await newsCollect({ id: item.id, collect_type: type });
  Toast(res.msg);
};

// 发送回复信息
const handleSend = async () => {
  await fetchNewsReview({ review_id: data.review_id, content: data.content });
};

// 点击回复回调，获取评论id
const handleReply = (item: Interaction.Review.List.Data) => {
  data.review_id = item.id;
  data.placeholder = `回复评论：${item.content}`;
  data.focus = true;
};

// 删除评论
const handleDel = (id: number) => {
  uni.showModal({
    title: '提示',
    content: '是否删除该条记录？',
    success: res => {
      if (res.confirm) {
        fetchNewsDelReview(id);
      }
    },
  });
};

// 失焦事件
const onBlur = () => {
  data.placeholder = '我有话要说...';
  data.focus = false;
};

/**
 * 接口相关
 */
// 资讯详情
const fetchNewsDetail = async (id: number) => {
  try {
    const res = await newsDetail({ id });
    data.info = res.data;
  } catch (e) {
    //TODO handle the exception
  }
};

// 评论列表
const upCallback = async (mescroll: any) => {
  try {
    let res = await newsReviewList({
      page: mescroll.num,
      limit: mescroll.size,
      information_id: data.id,
    });
    const curPageData = res?.data?.data || []; // 当前页数据
    if (mescroll.num == 1) data.list = []; // 第一页需手动制空列表
    data.list = data.list.concat(curPageData); //追加新数据
    mescroll.endByPage(curPageData.length, res?.data?.total);
  } catch (e) {
    //TODO handle the exception
    mescroll.endErr(); // 请求失败, 结束加载
  }
};

// 发布评论
const fetchNewsReview = async (params: { review_id: string; content: string }) => {
  try {
    await newsReview({
      id: data.id, // 帖子id
      ...params,
    });
    data.focus = false;
    data.reply_id = null;
    data.content = '';
    getMescroll()?.resetUpScroll();
  } catch (error) {}
};

// 删除评论
const fetchNewsDelReview = async (id: number) => {
  try {
    await newsDelReview({
      review_id: id + '',
    });
    getMescroll()?.resetUpScroll();
  } catch (error) {}
};

onLoad(option => {
  // 获取全局配置
  const configInfo = uni.getStorageSync('configInfo');
  if (Object.keys(configInfo || {})?.length > 0) {
    const parseInfo = JSON.parse(configInfo);
    data.configInfo = parseInfo;
  }
  data.id = option?.id;
  fetchNewsDetail(option?.id);
  // upCallback({ num: 1, size: 10 });

  uni.showShareMenu({
    withShareTicket: true,
    menus: ['shareAppMessage', 'shareTimeline'],
  });
});
</script>

<style lang="scss" scoped>
.container {
  .top_desc {
    padding: 40rpx 30rpx;
    background: white;
    .title {
      font-size: $fs-40;
    }
    .date {
      color: $sub;
    }
    .content {
      margin-top: 42rpx;
      font-size: 28rpx;
      color: $title;
    }
  }
  .raidus-lg {
    &::after{
      border: none;
    }
  }
}

.comment-list {
  background: white;
}

// 底部按钮
.btn {
  width: 100%;
  background: white;
  position: fixed;
  left: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  padding: 30rpx 30rpx $safe-bottom;
  box-sizing: border-box;
  border-top: 1rpx solid #e6e6e6;
  .input {
    flex: 1;
    height: 60rpx;
    line-height: 60rpx;
    border-radius: 30rpx;
    padding: 0 27rpx;
    color: #a5a5a5;
    font-size: $fs-28;
    background: #f2f2f2;
  }
  .dianzan,
  .collect {
    margin-left: 12rpx;
  }
}
</style>
